package com.example.servlet.manager;

import com.example.email.EmailSender;
import com.example.entity.*;
import com.example.service.OperationService;
import com.example.service.impl.OperationServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@WebServlet("/manager_order_operation")
public class mOrderOperationServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Manager manager = (Manager) req.getSession().getAttribute("manager");
        String orderId = req.getParameter("orderId");
        String actionType = req.getParameter("actionType");
        Order order = service.getOrderById(Integer.parseInt(orderId));
        User user = service.getUserById(order.getUserId());
        List<Ticket> tickets = service.getTicketsByOrderId(Integer.parseInt(orderId));
        LocalDateTime now = LocalDateTime.now();  // 获取当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 定义格式化模板
        String formattedNow = now.format(formatter);  // 格式化时间
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 定义格式化模板
        DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化今天的日期
        String formattedToday = today.format(formatterDate);
        try {
            switch (actionType) {
                case "approve":
                    //退钱
                    if(service.refundMoneyByUserIDtypeAndIDcard(user.getID_type(), user.getID_card(), order.getPrice())==0){
                        throw new Exception("Failed to refund money");
                    }
                    //航班状态
                    for(Ticket ticket:tickets){
                        if(Objects.equals(ticket.getSeat_type(), "经济舱")){
                            if(service.addEconomySpaceByFid(ticket.getFlightNo())==0){
                                throw new Exception("Failed to add economy space");
                            }
                        } else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                            if(service.addBusinessSpaceByFid(ticket.getFlightNo())==0){
                                throw new Exception("Failed to add business space");
                            }
                        }else{
                            if(service.addFirstSpaceByFid(ticket.getFlightNo())==0){
                                throw new Exception("Failed to add first space");
                            }
                        }
                    }
                    //订单状态
                    if(service.cancelOrder(order.getId(),  formattedNow)==0){
                        throw new Exception("Failed to cancel order");
                    }
                    //机票状态
                    if(service.cancelTicketByOrderId(Integer.parseInt(orderId))==0){
                        throw new Exception("Failed to cancel ticket");
                    }
                    service.commit();
                    String userEmail = service.getUserById(order.getUserId()).getEmail(); // 获取用户邮箱
                    if(userEmail != null && !userEmail.isEmpty()){
                        EmailSender.sendRefundSuccessNotification(userEmail, orderId);
                    }
                    break;
                case "refuse":
                    //机票状态
                    if(service.scheduledTicketStatus(Integer.parseInt(orderId))==0){
                        throw new Exception("Failed to set order id in ticket");
                    }
                    //订单状态
                    if(service.payOrderNoDate(Integer.parseInt(orderId))==0){
                        throw new Exception("Failed to pay order");
                    }
                    service.commit();
                    break;
                default:
                    break;
            }
            resp.sendRedirect("manager_order");
        } catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("order_operation_failure", new Object());
            resp.sendRedirect("manager_order");
        }
    }
}
